package hos.ui.item;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PaintDrawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.Map;

import hos.java.color.ColorConfig;
import hos.ui.ItemViewUtils;
import hos.ui.R;
import hos.ui.bean.CheckMore;
import hos.ui.bean.CheckSingle;

/**
 * <p>Title: ItemTitleLayout </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @version : 1.0
 * @date : 2023/6/9 17:11
 */
public abstract class ItemTitleLayout extends LinearLayout {

    private boolean isMustFull;
    private final TextView titleView;
    protected LinearLayout titleLayout;
    private TextView mustView;

    private final Paint bottomPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private final Line bottomLine;

    private String key;

    private String code;
    private String name;

    private TextView suffixTextOut;

    private ImageView suffixIconOut;

    public ItemTitleLayout(Context context) {
        this(context, null);
    }

    public ItemTitleLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ItemTitleLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
//        setShowDividers(SHOW_DIVIDER_BEGINNING);
//        setDividerDrawable(new ColorDrawable());
        setWillNotDraw(false);
        TypedArray typedArray =
                context.obtainStyledAttributes(attrs, R.styleable.ItemTitleLayout);
        try {
            String titleText = typedArray.getString(R.styleable.ItemTitleLayout_titleText);
            int titleColor = typedArray.getColor(
                    R.styleable.ItemTitleLayout_titleColor,
                    ColorConfig.black87
            );
            //px
            int titleTextSize = typedArray.getDimensionPixelSize(
                    R.styleable.ItemTitleLayout_titleTextSize,
                    applyUnit(TypedValue.COMPLEX_UNIT_SP, 15f)
            );
            int titleTextMinHeight = typedArray.getDimensionPixelOffset(R.styleable.ItemTitleLayout_titleTextMinHeight, dp2px(48));
            int titleTextMinWidth = typedArray.getDimensionPixelOffset(R.styleable.ItemTitleLayout_titleTextMinWidth, 0);
            int titleTextWidth = ItemViewUtils.getLayoutParam(typedArray, R.styleable.ItemTitleLayout_titleTextWidth, LayoutParams.WRAP_CONTENT);

            isMustFull = typedArray.getBoolean(R.styleable.ItemTitleLayout_must, false);
            int mustColor = typedArray.getColor(
                    R.styleable.ItemTitleLayout_mustColor,
                    ColorConfig.red.shade300()
            );
            bottomLine = new Line();

            bottomLine.enable = typedArray.getBoolean(R.styleable.ItemTitleLayout_dividerEnable, false);

            titleView = new TextView(getContext());
            titleView.setTextSize(TypedValue.COMPLEX_UNIT_PX, titleTextSize);  //sp---当做sp在转换一次
            titleView.setTextColor(titleColor);
            int orientation = getOrientation();
            if (orientation == HORIZONTAL) {
                int titleHeight = ItemViewUtils.getLayoutParam(typedArray, R.styleable.ItemTitleLayout_titleHeight, LayoutParams.WRAP_CONTENT);
                LayoutParams layoutParams = new LayoutParams(titleTextWidth, titleHeight);
                layoutParams.rightMargin = dp2px(8);
                titleView.setLayoutParams(layoutParams);
                setGravity(Gravity.LEFT | Gravity.CENTER);
            } else {
                int titleHeight = ItemViewUtils.getLayoutParam(typedArray, R.styleable.ItemTitleLayout_titleHeight, LayoutParams.WRAP_CONTENT);
                titleView.setLayoutParams(new LayoutParams(titleTextWidth, titleHeight));
                titleLayout = new LinearLayout(getContext());
                titleLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, titleHeight));
                titleLayout.setOrientation(LinearLayout.HORIZONTAL);
                titleLayout.setGravity(Gravity.LEFT | Gravity.CENTER);
            }
            titleView.setGravity(Gravity.LEFT | Gravity.CENTER);
            titleView.setMinHeight(titleTextMinHeight);
            if (titleTextMinWidth != 0) {
                titleView.setMinWidth(titleTextMinWidth);
            }
            setTitle(titleText);
            if (titleLayout == null) {
                addView(titleView);
            } else {
                titleLayout.addView(titleView);
            }
            if (isMustFull) {
                setMustFull(mustColor);
            }


            if (bottomLine.enable) {
                bottomLine.color = typedArray.getColor(
                        R.styleable.ItemTitleLayout_dividerColor,
                        ColorConfig.grey.shade100()
                );
                bottomLine.height = typedArray.getDimensionPixelOffset(R.styleable.ItemTitleLayout_dividerLineHeight, dp2px(1));
                bottomLine.leftMargin = typedArray.getDimensionPixelOffset(R.styleable.ItemTitleLayout_dividerLeftMargin, 0);
                bottomLine.rightMargin = typedArray.getDimensionPixelOffset(R.styleable.ItemTitleLayout_dividerRightMargin, 0);

                bottomPaint.setColor(bottomLine.color);
                bottomPaint.setStyle(Paint.Style.FILL_AND_STROKE);
                bottomPaint.setStrokeWidth(bottomLine.height);
            }

            if (titleLayout != null) {
                addView(titleLayout);
            }

            initAttributeSet(context, attrs, defStyleAttr);


            // 右侧按钮
            int iconOut = typedArray.getResourceId(R.styleable.ItemTitleLayout_suffixIconOut, -1);
            Drawable iconOutDrawable = null;
            if (iconOut == -1) {
                iconOutDrawable = typedArray.getDrawable(R.styleable.ItemTitleLayout_suffixIconOut);
            }
            int suffixIconOutColorRes = typedArray.getResourceId(R.styleable.ItemTitleLayout_suffixIconOutColor, -1);
            int suffixIconOutColor;
            if (suffixIconOutColorRes == -1) {
                suffixIconOutColor = typedArray.getColor(R.styleable.ItemTitleLayout_suffixIconOutColor, -1);
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    suffixIconOutColor = getContext().getColor(suffixIconOutColorRes);
                } else {
                    suffixIconOutColor = getContext().getResources().getColor(suffixIconOutColorRes);
                }
            }
            // 右侧按钮
            if (iconOut == -1) {
                if (iconOutDrawable != null) {
                    if (suffixIconOutColor != -1) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            iconOutDrawable.setTint(suffixIconOutColor);
                        } else {
                            iconOutDrawable.setColorFilter(suffixIconOutColor, PorterDuff.Mode.SRC_ATOP);
                        }
                    }
                    setSuffixIconOutDrawable(iconOutDrawable);
                }
            } else {
                setSuffixIconOutResource(iconOut);
                if (suffixIconOutColor != -1) {
                    setSuffixIconOutColor(suffixIconOutColor);
                }
            }
            /// 添加右侧文字按钮
            String suffixTextOutText = typedArray.getString(R.styleable.ItemTitleLayout_suffixTextOut);
            int suffixTextOutColor = typedArray.getColor(
                    R.styleable.ItemTitleLayout_suffixTextOutColor,
                    ColorConfig.black87
            );
            //px
            int suffixTextOutSize = typedArray.getDimensionPixelSize(
                    R.styleable.ItemTitleLayout_suffixTextOutSize,
                    applyUnit(TypedValue.COMPLEX_UNIT_SP, 15f)
            );
            int suffixTextOutBackgroundRadius = typedArray.getDimensionPixelSize(R.styleable.ItemTitleLayout_suffixTextOutBackgroundRadius, 0);
            int suffixTextOutBackground = typedArray.getResourceId(R.styleable.ItemTitleLayout_suffixTextOutBackgroundColor, -1);
            int suffixTextOutBackgroundColor;
            if (suffixTextOutBackground == -1) {
                suffixTextOutBackgroundColor = typedArray.getColor(R.styleable.ItemTitleLayout_suffixTextOutBackgroundColor, 0);
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    suffixTextOutBackgroundColor = getContext().getColor(suffixTextOutBackground);
                } else {
                    suffixTextOutBackgroundColor = getContext().getResources().getColor(suffixTextOutBackground);
                }
            }
            if (!TextUtils.isEmpty(suffixTextOutText)) {
                setSuffixTextOut(suffixTextOutText);
                setSuffixTextOutColor(suffixTextOutColor);
                setSuffixTextOut(suffixTextOutText);
                getSuffixTextOut().setTextSize(TypedValue.COMPLEX_UNIT_PX, suffixTextOutSize);
                setSuffixTextOutBackgroundColor(suffixTextOutBackgroundColor);
                setSuffixTextOutBackgroundRadius(suffixTextOutBackgroundRadius);
            }

        } finally {
            typedArray.recycle();
        }


    }

    protected abstract void initAttributeSet(Context context, AttributeSet attrs, int defStyleAttr);

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //巨坑
        if (bottomLine == null) {
            return;
        }
        if (bottomLine.enable) {
            canvas.drawLine(
                    bottomLine.leftMargin,
                    getHeight() - bottomLine.height,
                    getMeasuredWidth() - bottomLine.rightMargin,
                    getHeight() - bottomLine.height,
                    bottomPaint
            );
        }
    }

    public TextView getTitleView() {
        return titleView;
    }

    public void setTitle(String titleText) {
        if (titleView == null) {
            return;
        }
        titleView.setText(titleText);
    }

    public String getTitle() {
        if (titleView.getText() == null) {
            return "";
        }
        String title = String.valueOf(titleView.getText());
        return title.replaceAll(":", "").replaceAll("：", "");
    }

    public abstract void setContent(Map<String, Object> map, String key);

    public abstract void setContent(CharSequence content);

    public abstract void clear();

    public void clearListener() {
        if (suffixTextOut != null) {
            suffixTextOut.setOnClickListener(null);
        }
        if (suffixIconOut != null) {
            suffixIconOut.setOnClickListener(null);
        }
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void showMust() {
        if (mustView != null) {
            mustView.setVisibility(VISIBLE);
        }
    }

    public void hideMust() {
        if (mustView != null) {
            mustView.setVisibility(GONE);
        }
    }

    private void setMustFull(int color) {
        isMustFull = true;
        if (mustView != null) {
            mustView.setTextColor(color);
            return;
        }
        int width = dp2px(16);
        float sp16 = sp2px(16);
        mustView = new TextView(getContext());
        mustView.setTextSize(TypedValue.COMPLEX_UNIT_PX, sp16);  //sp---当做sp在转换一次
        mustView.setTextColor(color);
        mustView.setLayoutParams(new LayoutParams(width, LayoutParams.MATCH_PARENT));
        mustView.setText("*");
        mustView.setGravity(Gravity.CENTER);
        if (titleLayout != null) {
            titleLayout.addView(mustView);
        } else {
            addView(mustView);
        }
    }

    public void setSuffixTextOutClickListener(OnClickListener iconClickListener) {
        if (suffixTextOut == null) {
            return;
        }
        suffixTextOut.setOnClickListener(iconClickListener);
    }

    public void setSuffixTextOut(String text) {
        getSuffixTextOut().setText(text);
    }

    public void setSuffixTextOutColor(int color) {
        getSuffixTextOut().setTextColor(color);
    }

    public void setSuffixTextOutSize(int size) {
        suffixTextOut.setTextSize(size);
    }

    public void setSuffixTextOutBackgroundColor(int color) {
        getSuffixTextOutBackground().getPaint().setColor(color);
    }

    public void setSuffixTextOutBackgroundRadius(int radius) {
        getSuffixTextOutBackground().setCornerRadius(radius);
    }

    public TextView getSuffixTextOut() {
        if (suffixTextOut != null) {
            return suffixTextOut;
        }
        suffixTextOut = genSuffixTextOut();
        if (getOrientation() == HORIZONTAL) {
            if (suffixTextOut != null) {
                addView(suffixTextOut);
            }
        } else if (titleLayout != null) {
            if (suffixTextOut != null) {
                titleLayout.addView(suffixTextOut);
            }
        }
        return suffixTextOut;
    }

    protected PaintDrawable getSuffixTextOutBackground() {
        TextView suffixTextOut = getSuffixTextOut();
        Drawable background = suffixTextOut.getBackground();
        if (background == null) {
            int dp8 = dp2px(8);
            int dp2 = dp2px(4);
            PaintDrawable paintDrawable = genPaintDrawable();
            paintDrawable.setPadding(dp8, dp2, dp8, dp2);
            suffixTextOut.setBackground(paintDrawable);
            return (PaintDrawable) suffixTextOut.getBackground();
        }
        if (background instanceof PaintDrawable) {
            return (PaintDrawable) background;
        }
        int dp8 = dp2px(8);
        int dp2 = dp2px(4);
        PaintDrawable paintDrawable = genPaintDrawable();
        paintDrawable.setPadding(dp8, dp2, dp8, dp2);
        suffixTextOut.setBackground(paintDrawable);
        return (PaintDrawable) suffixTextOut.getBackground();
    }

    private PaintDrawable genPaintDrawable() {
        return new PaintDrawable();
    }

    protected TextView genSuffixTextOut() {
        return new TextView(getContext());
    }

    public void setOnSuffixIconOutClickListener(OnClickListener iconClickListener) {
        if (suffixIconOut == null) {
            return;
        }
        suffixIconOut.setOnClickListener(iconClickListener);
    }

    public void setSuffixIconOutResource(int resource) {
        getSuffixIconOut().setImageResource(resource);
    }

    public void setSuffixIconOutDrawable(Drawable drawable) {
        getSuffixIconOut().setImageDrawable(drawable);
    }

    public void setSuffixIconOutColor(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getSuffixIconOut().setImageTintList(ColorStateList.valueOf(color));
        } else {
            getSuffixIconOut().setColorFilter(color);
        }
    }

    public ImageView getSuffixIconOut() {
        if (suffixIconOut != null) {
            return suffixIconOut;
        }
        suffixIconOut = genSuffixIconOut();
        int dp8 = dp2px(8);
        int dp2 = dp2px(4);
        if (getOrientation() == HORIZONTAL) {
            // 右侧按钮
            if (suffixIconOut != null) {
                suffixIconOut.setPadding(dp8, 0, dp8, 0);
                suffixIconOut.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
                addView(suffixIconOut);
            }
        } else if (titleLayout != null) {
            // 垂直方向
            if (suffixIconOut != null) {
                suffixIconOut.setPadding(dp8, dp2, dp8, dp2);
                suffixIconOut.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
                titleLayout.addView(suffixIconOut);
            }
        }
        return suffixIconOut;
    }

    protected ImageView genSuffixIconOut() {
        return new ImageView(getContext());
    }

    @Override
    public void setClickable(boolean clickable) {
        super.setClickable(clickable);
        if (suffixIconOut != null) {
            suffixIconOut.setClickable(clickable);
        }
        if (suffixTextOut != null) {
            suffixTextOut.setClickable(clickable);
        }
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        if (suffixIconOut != null) {
            suffixIconOut.setEnabled(enabled);
        }
        if (suffixTextOut != null) {
            suffixTextOut.setEnabled(enabled);
        }
    }

    public void removeSuffixOut() {
        if (suffixIconOut != null) {
            if (getOrientation() == HORIZONTAL) {
                removeView(suffixIconOut);
            } else {
                titleLayout.removeView(suffixIconOut);
            }
            suffixIconOut = null;
        }
        if (suffixTextOut != null) {
            if (getOrientation() == HORIZONTAL) {
                removeView(suffixTextOut);
            } else {
                titleLayout.removeView(suffixTextOut);
            }
            suffixTextOut = null;
        }
    }

    public static class Line {

        int color = 0;
        float height = 0f;
        float leftMargin = 0f;
        float rightMargin = 0f;
        boolean enable = false;
    }

    protected int applyUnit(int applyUnit, float value) {
        return (int) TypedValue.applyDimension(applyUnit, value, getResources().getDisplayMetrics());
    }

    /**
     * Value of dp to value of px.
     *
     * @param dpValue The value of dp.
     * @return value of px
     */
    public static int dp2px(final float dpValue) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    /**
     * Value of sp to value of px.
     *
     * @param spValue The value of sp.
     * @return value of px
     */
    public static int sp2px(final float spValue) {
        final float fontScale = Resources.getSystem().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }


    /**
     * 多选
     *
     * @param checkMore 选项
     */
    public void showMoreDialog(CheckMore checkMore, String split, View.OnClickListener listener) {
        new AlertDialog.Builder(getContext())
                .setTitle("请选择")
                .setMultiChoiceItems(checkMore.getTitleArray(), checkMore.getBoolArray(), new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        checkMore.check(which, isChecked);
                    }
                })
                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String[] check = checkMore.getCheck(split);
                        setContent(check[0]);
                        setTag(check[1]);
                        if (listener != null) {
                            listener.onClick(ItemTitleLayout.this);
                        }
                    }
                }).setPositiveButton("取消", null)
                .show();
    }

    /**
     * 单选
     *
     * @param checkSingle 选项
     */
    public void showSingleDialog(CheckSingle checkSingle, View.OnClickListener listener) {
        new AlertDialog.Builder(getContext())
                .setTitle("请选择")
                .setSingleChoiceItems(checkSingle.getTitleArray(), checkSingle.getIndex(), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setContent(checkSingle.title(which));
                        setTag(checkSingle.check(which));
                        dialog.dismiss();
                        if (listener != null) {
                            listener.onClick(ItemTitleLayout.this);
                        }
                    }
                })
                .show();
    }
}
